//
//  PushTieziViewController.m
//  Lucky28
//
//  Created by zr on 2018/8/2.
//  Copyright © 2018年 zr. All rights reserved.
//

#import "PushTieziViewController.h"

@interface PushTieziViewController ()<UITextViewDelegate,UIImagePickerControllerDelegate, UINavigationControllerDelegate>{
    
    UIImagePickerController *_imagePickerController;
}

@property (nonatomic, weak)UIButton * pictureButton;
@property (nonatomic, weak)UITextView * textView;
@property (nonatomic, weak)UIButton * okButton;
@property (nonatomic, strong)UIAlertController * alertVC;
@property (nonatomic, copy)NSString * images;

@end

@implementation PushTieziViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    _imagePickerController = [[UIImagePickerController alloc] init];
    _imagePickerController.delegate = self;
    _imagePickerController.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
    _imagePickerController.allowsEditing = YES;
    
    [self setupNav];
    [self setupUI];
    [self setupAlertVC];
}

- (void)setupNav{
    
    self.title = @"发帖子";
    
    UIButton * backButton = [[UIButton alloc] init];
    
    backButton.frame = CGRectMake(0, 0, 12 * SCREENH6, 20 * SCREENH6);
    [backButton setImage:[UIImage imageNamed:@"1返回"] forState:UIControlStateNormal];
    [backButton addTarget:self action:@selector(backToView) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem * leftButton = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    
    self.navigationItem.leftBarButtonItem = leftButton;
    
}

- (void)setupUI{
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    UIButton * pictureButton = [UIButton new];
    
    [pictureButton setImage:ImageNamed(@"shangchuan") forState:UIControlStateNormal];
    [pictureButton addTarget:self action:@selector(ClickPictureButton) forControlEvents:UIControlEventTouchUpInside];
    
    self.pictureButton = pictureButton;
    
    [self.view addSubview:self.pictureButton];
    
    
    // 创建textView
    UITextView *textView =[[UITextView alloc]initWithFrame:CGRectMake(25 * SCREENH6,255 * SCREENH6,SCREEN_WIDTH - 50 * SCREENH6,150 * SCREENH6)];
    textView.backgroundColor= [UIColor whiteColor];
    textView.text = @"写点什么......";
    textView.font = [UIFont systemFontOfSize:15 * SCREENH6];
    textView.textColor = ColorWithRGB(0xe7e7e7);
    textView.layer.borderWidth = 1.0f;
    textView.layer.borderColor = [ColorWithRGB(0xe7e7e7) CGColor];
    textView.delegate = self;
    
    self.textView = textView;
    
    [self.view addSubview:self.textView];
    
    
    UIButton * okButton = [UIButton new];
    
    [okButton setTitle:@"发表" forState:UIControlStateNormal];
    [okButton setTitleColor:ColorWithRGB(0xBDBDBD) forState:UIControlStateNormal];
    [okButton setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
    [okButton setBackgroundImage:ImageNamed(@"fabiao") forState:UIControlStateNormal];
    [okButton setBackgroundImage:ImageNamed(@"fabiao2") forState:UIControlStateSelected];
    [okButton addTarget:self action:@selector(clickOkButton) forControlEvents:UIControlEventTouchUpInside];
    okButton.titleLabel.font = [UIFont systemFontOfSize:17 * SCREENH6];
    
    self.okButton = okButton;
    
    [self.view addSubview:self.okButton];
}


- (void)viewDidLayoutSubviews{
    
    [self.pictureButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.view).offset(25 * SCREENH6);
        make.leading.mas_equalTo(self.view).offset(25 * SCREENH6);
        make.trailing.mas_equalTo(self.view).offset(-25 * SCREENH6);
        make.height.mas_equalTo(215 * SCREENH6);
    }];
    
    [self.okButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.mas_equalTo(self.pictureButton);
        make.height.mas_equalTo(35 * SCREENH6);
        make.top.mas_equalTo(self.textView.mas_bottom).offset(80 * SCREENH6);
    }];
}


- (void)setupAlertVC{
    
    self.alertVC = [UIAlertController alertControllerWithTitle:@"" message:@"选择照片方式" preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction * camerAction = [UIAlertAction actionWithTitle:@"相机" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        self->_imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
        
        [self presentViewController:self->_imagePickerController animated:YES completion:nil];
    }];
    
    UIAlertAction * albumsAction = [UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        self->_imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        
        [self presentViewController:self->_imagePickerController animated:YES completion:nil];
    }];
    
    UIAlertAction * cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    
    [self.alertVC addAction:camerAction];
    [self.alertVC addAction:albumsAction];
    [self.alertVC addAction:cancelAction];
    
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(nullable NSDictionary<NSString *,id> *)editingInfo

{

    [self.pictureButton setImage:image forState:UIControlStateNormal];
    
//    if(picker.sourceType == UIImagePickerControllerSourceTypeCamera)
//        
//    {
//        //图片存入相册
//        
//        UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);
//        
//    }
    NSUserDefaults * userDefaults = [NSUserDefaults standardUserDefaults];
    
    NSString * token = [userDefaults objectForKey:@"token"];
    
    NSData *frontImageData = UIImageJPEGRepresentation(image,0.5);
    
    
    NSDictionary * dic = @{@"files":frontImageData,@"token":token};
    
    [[NetworkTool sharedTools] POST:@"/index/Note/noteupload" parameters:dic constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        // 设置时间格式
        formatter.dateFormat  = @"yyyyMMddHHmmss";
        NSString *str  = [formatter stringFromDate:[NSDate date]];
        NSString *fileName  = [NSString stringWithFormat:@"%@.png", str];
        [formData appendPartWithFileData:frontImageData name:@"files" fileName:fileName mimeType:@"image/png"];
        
        
    } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        
        NSInteger code = [responseObject[@"status"] integerValue];
        
        if (code == 200){
            
            self.images = [NSString stringWithFormat:@"%@",responseObject[@"data"]];
        }else{
            
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
    
    
    [self dismissViewControllerAnimated:YES completion:nil];
    
}

//进入拍摄页面点击取消按钮

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker

{
    
    [self dismissViewControllerAnimated:YES completion:nil];
    
}


- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    
//   self.okButton.selected = YES;
    [self.textView resignFirstResponder];
}

- (void)ClickPictureButton{
    
    
    [self presentViewController:self.alertVC animated:YES completion:nil];
}

- (void)clickOkButton{
    
    NSUserDefaults * userDefaults = [NSUserDefaults standardUserDefaults];
    
    NSString * token = [userDefaults objectForKey:@"token"];
    
    NSDictionary * dict = @{@"token":token,@"content":self.textView.text,@"type":@"5",@"images":self.images,@"title":self.textView.text};
    
    [[NetworkTool sharedTools] POST:@"/index/Note/add" parameters:dict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
//        NSLog(@"==%@",responseObject);
        
        int status = [responseObject[@"status"] intValue];
        
        if (status == 200) {
            
            [self.navigationController popViewControllerAnimated:YES];
            
            [[NSNotificationCenter defaultCenter] postNotificationName:@"GetPictureData" object:nil];
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
    
}

#pragma mark - UITextViewDelegate
- (void)textViewDidEndEditing:(UITextView *)textView
{
    
    [self.textView resignFirstResponder];
    
    if(textView.text.length < 1){
        textView.text = @"写点什么......";
        textView.textColor = ColorWithRGB(0xbebebe);
    }else{
        
        self.okButton.selected = YES;
    }
}

- (void)textViewDidBeginEditing:(UITextView *)textView
{
    if([textView.text isEqualToString:@"写点什么......"]){
        textView.text=@"";
        textView.textColor=[UIColor blackColor];
    }
}


- (void)backToView{
    
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
